const { createServer } = require('http');
const next = require('next');
const { WebSocketServer } = require('ws');
const mysql = require('mysql2/promise');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'db_react'
};

app.prepare().then(() => {
    const server = createServer((req, res) => {
        handle(req, res);
    });

    // 创建 WebSocket 服务器
    const wss = new WebSocketServer({ server });

    // 存储每个连接的用户信息
    const clients = new Map();

    wss.on('connection', (ws, req) => {
        console.log('服务器已连接！');

        ws.on('message', async (message) => {
            console.log(`接受到的消息 => ${message}`);

            // 解析 JSON 格式的消息
            const msgData = JSON.parse(message);

            // 注册用户连接
            if (msgData.type === 'register') {
                const { userId } = msgData;
                clients.set(userId, ws);
                console.log(`用户 ${userId} 已注册`);
                return;
            }

            const formatMySQLTimestamp = (isoString) => {
                const date = new Date(isoString);
                const year = date.getUTCFullYear();
                const month = String(date.getUTCMonth() + 1).padStart(2, '0');
                const day = String(date.getUTCDate()).padStart(2, '0');
                const hours = String(date.getUTCHours()).padStart(2, '0');
                const minutes = String(date.getUTCMinutes()).padStart(2, '0');
                const seconds = String(date.getUTCSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            };
            const mysqlTimestamp = formatMySQLTimestamp(msgData.timestamp);

            // 保存消息到数据库
            try {
                const connection = await mysql.createConnection(dbConfig);
                const [rows] = await connection.execute(
                    'INSERT INTO db_messages (user_id, work_id, message, timestamp,target_user_id) VALUES (?, ?, ?, ?, ?)',
                    [msgData.user_id, msgData.chat_id, msgData.message,mysqlTimestamp,msgData.targetUserId]  // 这里使用 chat_id 保存工作 ID
                );
                console.log('消息保存:', rows);
                await connection.end();
            } catch (error) {
                console.error('数据库报错:', error);
                ws.send(JSON.stringify({ status: 'error', message: error.message }));
                return;
            }

            // 转发消息给目标用户
            const recipientSocket = clients.get(msgData.targetUserId);
            if (recipientSocket) {
                const outgoingMessage = {
                    status: 'success',
                    chat_id: msgData.chat_id,
                    sender_id: msgData.user_id,
                    message: msgData.message,
                    timestamp: msgData.timestamp
                };
                recipientSocket.send(JSON.stringify(outgoingMessage));
                console.log(`消息已发送给用户 ${msgData.targetUserId}`);
            } else {
                console.error('目标用户未连接:', msgData.targetUserId);
            }
        });

        ws.on('close', () => {
            console.log('断开连接');
            // 移除关闭的连接
            for (const [userId, socket] of clients.entries()) {
                if (socket === ws) {
                    clients.delete(userId);
                    console.log(`用户 ${userId} 已断开连接`);
                    break;
                }
            }
        });
    });

    server.listen(8090, (err) => {
        if (err) throw err;
        console.log('> Ready on http://localhost:8090');
    });
});
